from flask import Flask
from flask import request
import mysql
import json
import time

app = Flask(__name__)
config_file = []

with open('/root/config') as file:
    for line in file:
        config_file.append(line.strip())

my = mysql.MYSQL(host=config_file[0], user='test', password=config_file[1], db='test')


def get_device():
    q = my.query('select d.device_id, c.cabinet_name, d.u_id, d.device_name, d.device_status, d.warning_time, m.status_time from device d, cabinet c, (select device_id, count(*) as status_time from maintenence where device_status = 1 group by device_id, device_status) m where d.device_id = m.device_id and d.cabinet_id = c.cabinet_id;')
    data = json.dumps(q)
    return data

def get_history(device_id):
    q = my.query('select * from maintenence where device_id = {}'.format(device_id))
    data = json.dumps(q)
    return data

def commit_info(device_id, info):
    my.update('insert into maintenence values ({}, {}, "{}", {})'.format(device_id, 1, info, round(time.time())))


@app.route("/")
def hello():
    r = request.args.get("request")
    if r == 'get_device':
        data = get_device()
        return data
    if r == 'get_history':
        device_id = request.args.get("device_id")
        data = get_history(device_id)
        return data
    elif r == 'commit_info':
        device_id = request.args.get("device_id")
        info = request.args.get("info")
        print(device_id, info)
        commit_info(device_id, info)



if __name__ == "__main__":
    app.run(host='0.0.0.0', port='5000', debug=True)